package com.merchant.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.merchant.entity.RuiShengUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @program: merchant-register
 * @description: 沈阳二类卡信息
 * @author: Vincent
 * @create: 2019-03-01 15:44
 **/
@Service("shenYangAccountAssistant")
public class ShenYangAccountAssistant {
    private static final Logger log = LoggerFactory.getLogger("ShenYangAccountAssistant");

    public static final String CACHE_USER_KEY = "SHENYANG_ACCOUNT_ASSISTANT_USER";

    private static String MCH_ID = "00020023";

    @Autowired
    private AddressHelper addressHelper;

    @Autowired
    private BankHelper bankHelper;

    @Autowired
    private RedisUtil redisUtil;

    private static final String PATH = "E:\\滨农进件资料\\沈阳\\沈阳二类卡进件-20190309\\银行-沈阳-0309\\190309天津滨农二类户银行资料.xlsx";
    private static final String SY_USER_ROOT_PATH = "E:\\滨农进件资料\\沈阳\\沈阳二类卡进件-20190309\\银行-沈阳-0309";


    /**
     * 读取文件并上传用户的证件信息
     *
     * @return List
     */
    public List<RuiShengUserInfo> getUserFromFile() {
        // 先从缓存中获取
        Map<String, Object> userMap = redisUtil.hgetAll(CACHE_USER_KEY);
        if (userMap != null && userMap.size() > 0) {
            List<RuiShengUserInfo> userList = Lists.newArrayList();
            for (String key : userMap.keySet()) {
                RuiShengUserInfo user = (RuiShengUserInfo) userMap.get(key);
                userList.add(user);
            }
            if (userList != null && userList.size() > 0) {
                return userList;
            }
        }

        // 读取文件获取二类卡信息
        List<RuiShengUserInfo> fileUserList = getBankInfo();
        // 上传证件照
        List<RuiShengUserInfo> userList = uploadCardPic(fileUserList);
        // 设置到缓存中
        if (userList != null && userList.size() > 0) {
            for (RuiShengUserInfo item : userList) {
                redisUtil.hset(CACHE_USER_KEY, item.getPayname().trim(), item);
            }
        }

        return userList;
    }

    public List<RuiShengUserInfo> parseUser() {
        String data = "{\"code\":0,\"data\":[{\"accopenpic\":\"\",\"address\":\"\",\"area\":\"\",\"areaname\":\"\",\"bankname\":\"兴业银行\",\"bankno\":\"3090000\",\"branchname\":\"兴业银行沈阳和平支行\",\"branchno\":\"309221015201\",\"buslicpic\":\"/uploads/71/0a7837535e53703d077c6ad667e942.jpg\",\"cardarea\":\"210102\",\"cardareaname\":\"和平区\",\"cardcity\":\"210100\",\"cardcityname\":\"沈阳市\",\"cardno\":\"622908423039235518\",\"cardprovince\":\"210000\",\"cardprovincename\":\"辽宁省\",\"cashierpic\":\"\",\"certno\":\"210102198702154412\",\"certtype\":\"1\",\"city\":\"\",\"cityname\":\"\",\"createTime\":null,\"doorpic\":\"\",\"ecardno\":\"6231099101000703739\",\"email\":\"\",\"fee\":\"0\",\"handpic\":\"/uploads/b2/dad7bc6c709db4a7b637379fdd27b9.jpg\",\"id\":0,\"legbackpic\":\"/uploads/c8/b6279a0a4d57a9de6ac87c1cce3075.jpg\",\"legelcertno\":\"210102198702154412\",\"legelname\":\"李众\",\"legfrontpic\":\"/uploads/71/0a7837535e53703d077c6ad667e942.jpg\",\"mchid\":\"00020023\",\"modifyTime\":null,\"name\":\"\",\"payname\":\"李众\",\"payphone\":\"13842014531\",\"phone\":\"\",\"province\":\"\",\"provincename\":\"\",\"rate\":\"\",\"remark\":\"\",\"status\":\"\",\"submchid\":\"\",\"type\":\"1\",\"version\":0},{\"accopenpic\":\"\",\"address\":\"\",\"area\":\"\",\"areaname\":\"\",\"bankname\":\"兴业银行\",\"bankno\":\"3090000\",\"branchname\":\"兴业银行沈阳和平支行\",\"branchno\":\"309221015201\",\"buslicpic\":\"/uploads/83/9b0dd85729d1ba18b58c0073112826.jpg\",\"cardarea\":\"210102\",\"cardareaname\":\"和平区\",\"cardcity\":\"210100\",\"cardcityname\":\"沈阳市\",\"cardno\":\"622908423032514117\",\"cardprovince\":\"210000\",\"cardprovincename\":\"辽宁省\",\"cashierpic\":\"\",\"certno\":\"210102198512285315\",\"certtype\":\"1\",\"city\":\"\",\"cityname\":\"\",\"createTime\":null,\"doorpic\":\"\",\"ecardno\":\"6231099101000703747\",\"email\":\"\",\"fee\":\"0\",\"handpic\":\"/uploads/87/40411322a7e33f5abbcf1f001b32c8.jpg\",\"id\":0,\"legbackpic\":\"/uploads/d6/3dbd62d2b22922c990a2467ae7a047.jpg\",\"legelcertno\":\"210102198512285315\",\"legelname\":\"裴晓波\",\"legfrontpic\":\"/uploads/83/9b0dd85729d1ba18b58c0073112826.jpg\",\"mchid\":\"00020023\",\"modifyTime\":null,\"name\":\"\",\"payname\":\"裴晓波\",\"payphone\":\"13718813762\",\"phone\":\"\",\"province\":\"\",\"provincename\":\"\",\"rate\":\"\",\"remark\":\"\",\"status\":\"\",\"submchid\":\"\",\"type\":\"1\",\"version\":0},{\"accopenpic\":\"\",\"address\":\"\",\"area\":\"\",\"areaname\":\"\",\"bankname\":\"建设银行\",\"bankno\":\"1050000\",\"branchname\":\"中国建设银行股份有限公司沈阳胜民支行\",\"branchno\":\"105221016117\",\"buslicpic\":\"/uploads/05/0d8b886fce0b408e266618e5cefb70.jpg\",\"cardarea\":\"210102\",\"cardareaname\":\"和平区\",\"cardcity\":\"210100\",\"cardcityname\":\"沈阳市\",\"cardno\":\"6217000730023110840\",\"cardprovince\":\"210000\",\"cardprovincename\":\"辽宁省\",\"cashierpic\":\"\",\"certno\":\"210102196212223412\",\"certtype\":\"1\",\"city\":\"\",\"cityname\":\"\",\"createTime\":null,\"doorpic\":\"\",\"ecardno\":\"6231099101000703994\",\"email\":\"\",\"fee\":\"0\",\"handpic\":\"/uploads/f2/f9e29123482a30f2d168d423dc7f61.jpg\",\"id\":0,\"legbackpic\":\"/uploads/b9/f657f766dba16778abb3dd2d3964ab.jpg\",\"legelcertno\":\"210102196212223412\",\"legelname\":\"曲勇\",\"legfrontpic\":\"/uploads/05/0d8b886fce0b408e266618e5cefb70.jpg\",\"mchid\":\"00020023\",\"modifyTime\":null,\"name\":\"\",\"payname\":\"曲勇\",\"payphone\":\"17602474907\",\"phone\":\"\",\"province\":\"\",\"provincename\":\"\",\"rate\":\"\",\"remark\":\"\",\"status\":\"\",\"submchid\":\"\",\"type\":\"1\",\"version\":0},{\"accopenpic\":\"\",\"address\":\"\",\"area\":\"\",\"areaname\":\"\",\"bankname\":\"工商银行\",\"bankno\":\"1020000\",\"branchname\":\"中国工商银行沈阳青年大街支行\",\"branchno\":\"102221000212\",\"buslicpic\":\"/uploads/17/e1b13fe230112fb3ea08696eba602f.jpg\",\"cardarea\":\"210103\",\"cardareaname\":\"沈河区\",\"cardcity\":\"210100\",\"cardcityname\":\"沈阳市\",\"cardno\":\"6222033301008455922\",\"cardprovince\":\"210000\",\"cardprovincename\":\"辽宁省\",\"cashierpic\":\"\",\"certno\":\"210882198011271521\",\"certtype\":\"1\",\"city\":\"\",\"cityname\":\"\",\"createTime\":null,\"doorpic\":\"\",\"ecardno\":\"6231099101000687957\",\"email\":\"\",\"fee\":\"0\",\"handpic\":\"/uploads/9a/554a7c24624d5d36d536cc46e29c97.jpg\",\"id\":0,\"legbackpic\":\"/uploads/bd/5401d3bdd342d9812e8278223f3826.jpg\",\"legelcertno\":\"210882198011271521\",\"legelname\":\"王丹\",\"legfrontpic\":\"/uploads/17/e1b13fe230112fb3ea08696eba602f.jpg\",\"mchid\":\"00020023\",\"modifyTime\":null,\"name\":\"\",\"payname\":\"王丹\",\"payphone\":\"15710515655\",\"phone\":\"\",\"province\":\"\",\"provincename\":\"\",\"rate\":\"\",\"remark\":\"\",\"status\":\"\",\"submchid\":\"\",\"type\":\"1\",\"version\":0},{\"accopenpic\":\"\",\"address\":\"\",\"area\":\"\",\"areaname\":\"\",\"bankname\":\"兴业银行\",\"bankno\":\"3090000\",\"branchname\":\"兴业银行沈阳和平支行\",\"branchno\":\"309221015201\",\"buslicpic\":\"/uploads/d1/10132e9c794cc8751741140f0959e6.jpg\",\"cardarea\":\"210102\",\"cardareaname\":\"和平区\",\"cardcity\":\"210100\",\"cardcityname\":\"沈阳市\",\"cardno\":\"622908423039535719\",\"cardprovince\":\"210000\",\"cardprovincename\":\"辽宁省\",\"cashierpic\":\"\",\"certno\":\"210102196008164750\",\"certtype\":\"1\",\"city\":\"\",\"cityname\":\"\",\"createTime\":null,\"doorpic\":\"\",\"ecardno\":\"6231099101000707318\",\"email\":\"\",\"fee\":\"0\",\"handpic\":\"/uploads/47/8e33dbbfd9c7e3a3a4dc4a8c001a39.jpg\",\"id\":0,\"legbackpic\":\"/uploads/4c/68e44cb74ba4c963e3b5ca541fb6f9.jpg\",\"legelcertno\":\"210102196008164750\",\"legelname\":\"杨玉斌\",\"legfrontpic\":\"/uploads/d1/10132e9c794cc8751741140f0959e6.jpg\",\"mchid\":\"00020023\",\"modifyTime\":null,\"name\":\"\",\"payname\":\"杨玉斌\",\"payphone\":\"15524503015\",\"phone\":\"\",\"province\":\"\",\"provincename\":\"\",\"rate\":\"\",\"remark\":\"\",\"status\":\"\",\"submchid\":\"\",\"type\":\"1\",\"version\":0},{\"accopenpic\":\"\",\"address\":\"\",\"area\":\"\",\"areaname\":\"\",\"bankname\":\"兴业银行\",\"bankno\":\"3090000\",\"branchname\":\"兴业银行沈阳长白支行\",\"branchno\":\"309221015189\",\"buslicpic\":\"/uploads/ab/65b47d525ed7d6f030929acdb8b3a2.jpg\",\"cardarea\":\"210102\",\"cardareaname\":\"和平区\",\"cardcity\":\"210100\",\"cardcityname\":\"沈阳市\",\"cardno\":\"622908423038579411\",\"cardprovince\":\"210000\",\"cardprovincename\":\"辽宁省\",\"cashierpic\":\"\",\"certno\":\"210102195803223030\",\"certtype\":\"1\",\"city\":\"\",\"cityname\":\"\",\"createTime\":null,\"doorpic\":\"\",\"ecardno\":\"6231099101000706724\",\"email\":\"\",\"fee\":\"0\",\"handpic\":\"/uploads/88/4626fffbcbb1239e1cbaa3b23dfa22.jpg\",\"id\":0,\"legbackpic\":\"/uploads/28/2bea802578337223722c6072d24308.jpg\",\"legelcertno\":\"210102195803223030\",\"legelname\":\"周涛\",\"legfrontpic\":\"/uploads/ab/65b47d525ed7d6f030929acdb8b3a2.jpg\",\"mchid\":\"00020023\",\"modifyTime\":null,\"name\":\"\",\"payname\":\"周涛\",\"payphone\":\"15524501075\",\"phone\":\"\",\"province\":\"\",\"provincename\":\"\",\"rate\":\"\",\"remark\":\"\",\"status\":\"\",\"submchid\":\"\",\"type\":\"1\",\"version\":0}],\"message\":\"操作成功\",\"ok\":true,\"timestamp\":1551593834823}";

        JSONObject json = JSONObject.parseObject(data);
        JSONArray jsonArray = json.getJSONArray("data");

        List<RuiShengUserInfo> userList = Lists.newArrayList();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject item = jsonArray.getJSONObject(i);
            RuiShengUserInfo user = JSONObject.parseObject(item.toJSONString(), RuiShengUserInfo.class);

            System.out.println(user);
            redisUtil.hset(CACHE_USER_KEY, user.getPayname().trim(), user);

            userList.add(user);
        }
        return userList;
    }


    /**
     * 处理用户的证件照图片地址
     *
     * @param userList 用户列表
     * @return List
     */
    public List<RuiShengUserInfo> uploadCardPic(List<RuiShengUserInfo> userList) {
        if (userList == null) {
            log.error("uploadCardPic() 上传证件照片，用户列表为空");
            return null;
        }

        List<RuiShengUserInfo> newUserList = Lists.newArrayList();

        for (RuiShengUserInfo user : userList) {
            String userName = user.getPayname();

            String cardPicPath = SY_USER_ROOT_PATH + File.separator + userName;
            File cardPicFolder = new File(cardPicPath);
            if (!cardPicFolder.exists()) {
                log.error("uploadCardPic() 用户[" + userName + "]的身份证照片目录不存在");
                continue;
            }

            File frontFile = new File(cardPicPath + File.separator + "1.jpg");
            String frontUrl = FileUploadHandler.uploadFile(frontFile);
            user.setBuslicpic(frontUrl);
            user.setLegfrontpic(frontUrl);

            File backFile = new File(cardPicPath + File.separator + "2.jpg");
            String backUrl = FileUploadHandler.uploadFile(backFile);
            user.setLegbackpic(backUrl);

            File handFile = new File(cardPicPath + File.separator + "3.jpg");
            String handUrl = FileUploadHandler.uploadFile(handFile);
            user.setHandpic(handUrl);

            try {
                user.checkCertPic();
            } catch (Exception e) {
                log.error("uploadCardPic() 用户[" + userName + "]证件图片地址异常=" + e.getMessage());
                continue;
            }
            newUserList.add(user);
        }

        return newUserList;
    }


    /**
     * 读取文件获取二类卡信息
     *
     * @return List
     */
    public List<RuiShengUserInfo> getBankInfo() {
        List<RuiShengUserInfo> userList = Lists.newArrayList();
        try {

            List<Object> dataList = ExcelUtils.readExcel(PATH, 1, 2, "ALL");

            for (Object item : dataList) {
                List<String> datas = (List<String>) item;
                if (datas.get(0) == null) continue;

                // 基础信息
                String payName = datas.get(1);
                String payPhone = datas.get(2);
                String ecardNo = datas.get(3);
                String cardNo = datas.get(4);

                // 银行信息
                String bankName = datas.get(5);
                String branchName = datas.get(6);
                String bankCode = bankHelper.getBankCode(bankName);
                String branchCode = bankHelper.getBranchCode(bankCode, branchName);

                // 地址
                String province = datas.get(8);
                String city = datas.get(9);
                String area = datas.get(10);
                String provinceCode = addressHelper.getProvinceCode(province);
                String cityCode = addressHelper.getCityCode(provinceCode, city);
                String areaCode = addressHelper.getAreaCode(cityCode, area);

                // 身份证
                String certNo = datas.get(7);

                // 检查是否合格
                RuiShengUserInfo user = RuiShengUserInfo.genUserInfo(MCH_ID, payName, certNo, payPhone, cardNo, ecardNo,
                        bankCode, bankName, branchCode, branchName, provinceCode,
                        province, cityCode, city, areaCode, area,
                        "", "", "", "");

                try {
                    user.initCheckParams();
                } catch (Exception e) {
                    log.error("初始化用户数据，当前用户有关键属性值为空：" + e.getMessage() + ", 用户信息=" + JSONObject.toJSONString(user));
                    continue;
                }

                userList.add(user);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return userList;
    }


    public RuiShengUserInfo get(String name) {

        return null;
    }


    public static RuiShengUserInfo getLiuYongQi(String merchantName, String province, String city, String area, String address,
                                                String doorpic, String pname, String cname, String aname, String phone,
                                                String email, String remark) {
        RuiShengUserInfo userInfo = new RuiShengUserInfo();
        userInfo.setMchid(MCH_ID);


        userInfo.setPayname("刘永琪");
        userInfo.setLegelname("刘永琪");
        userInfo.setLegelcertno("440305200005092028");
        userInfo.setCertno("440305200005092028");
        userInfo.setPayphone("17841142066");

        userInfo.setEcardno("6231099101000705767");
        userInfo.setCardno("6217007200081350293");

        userInfo.setBankno("1050000");
        userInfo.setBranchno("105584001299");
        userInfo.setBankname("建设银行");
        userInfo.setBranchname("中国建设银行股份有限公司深圳西乡支行");

        userInfo.setCardprovince("440000");
        userInfo.setCardcity("440300");
        userInfo.setCardarea("440304");
        userInfo.setCardprovincename("广东省");
        userInfo.setCardcityname("深圳市");
        userInfo.setCardareaname("福田区");

        userInfo.setBuslicpic("/uploads/c8/7102e49106dd3fec614409e5219a6a.jpg");
        userInfo.setLegfrontpic("/uploads/94/7664e95fe949394917b4ef726ce239.jpg");
        userInfo.setLegbackpic("/uploads/c8/7102e49106dd3fec614409e5219a6a.jpg");
        userInfo.setHandpic("/uploads/87/01fc9dec4040e72708628ce3dd13f1.jpg");

        userInfo.setName(merchantName);
        userInfo.setProvince(province);
        userInfo.setCity(city);
        userInfo.setArea(area);
        userInfo.setAddress(address);
        userInfo.setEmail(email);
        userInfo.setPhone(phone);

        userInfo.setType("1");
        userInfo.setCerttype("1");
        userInfo.setDoorpic(doorpic);

        userInfo.setRate("31");
        userInfo.setRemark(remark);

        userInfo.setProvincename(pname);
        userInfo.setCityname(cname);
        userInfo.setAreaname(aname);

        return userInfo;
    }


}
